import httplib,re
#-*- coding: utf-8 -*-
USER_AGENT='Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.12) \
                        Gecko/20050922 Firefox/1.0.7 (Debian package 1.0.7-1)'

def conect_dict(post):
    header = httplib.HTTPConnection('www.freedict.com')
    header.putrequest('POST', 'http://www.freedict.com/onldict/onldict.php')
    header.putheader('User-Agent', USER_AGENT)
    header.putheader('Content-Type', 'application/x-www-form-urlencoded')
    header.putheader('Content-Length', len(post))
    header.endheaders()
    header.send(post)
    return header.getresponse().read()

def en_jap(word):
    #en-jap
    post='search=%s\
        &exact=true&max=10&\
        from=English&\
        to=Japanese\
        &fname=eng2jap1&back=jap.html'%word
    src=conect_dict(post)
    #print src
    transl=re.findall('<td class="result-l-blue">.*?</td>\n.*?<td class="result-r-blue"><strong>(.*?)</strong></td>',src)
    if transl == []: 
        return 'Такого слова нет в словаре Т_Т'
    else:
        #print transl
        jp=transl[0]
        return jp
def jap_en(word):
    post='search=%s&exact=true&max=10&\
    to=English\
    &from=Japanese\
    &fname=eng2jap2&back=jap.html'%word
    src=conect_dict(post)
    
    transl=re.findall('<td class="result-l-blue">.*?</td>\n.*?<td class="result-r-blue"><strong>(.*?)</strong></td>',src)
    #print transl
    if transl == []: 
        return 'Такого слова нет в словаре Т_Т'
    else:
        en=', '.join(transl)
        return en

def rus_eng(word):
    u=unicode(word, 'utf8')
    word=u.encode('cp1251')
    post='search=%s\
    &exact=true&max=10&\
    to=English\
    &from=Russian\
    &fname=eng2rus2&back=rus.html'%word
    src=conect_dict(post)
    transl=re.findall('<td class="result-l-blue">.*?</td>\n.*?<td class="result-r-blue"><strong>(.*?)</strong></td>',src)
    if transl == []: 
        return 'Такого слова нет в словаре Т_Т'
    else:
        return transl[0]
def eng_rus(word):
    post='search=%s\
    &exact=true&max=10&\
    to=Russian\
    &from=English\
    &fname=eng2rus1&back=rus.html'%word
    src=conect_dict(post)
    transl=re.findall('<td class="result-l-blue">.*?</td>\n.*?<td class="result-r-blue"><strong>(.*?)</strong></td>',src)
    if transl == []: 
        return 'Такого слова нет в словаре Т_Т'
    else:
        cyrillic_cp1251=unicode(transl[0] , 'cp1251')
        return cyrillic_cp1251.encode('utf8')


#print eng_rus('love')